/**
 * 
 */
package com.antilia.infomaresme.pages;

import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.IModel;

import com.antilia.infomaresme.InfomaresmeApplication;
import com.antilia.infomaresme.data.dataobjects.Category;

/**
 * @author Ernesto
 *
 */
public abstract class CategoriesListPanel extends Panel {

	private static final long serialVersionUID = 1L;
	
	private Category selected;
	
	
	/**
	 * @param id
	 */
	public CategoriesListPanel(String id, Category selected, IModel<String> title) {
		super(id);
		this.selected = selected;
		add(new Label("title", title));
	}
	
	@Override
	protected void onBeforeRender() {						
		RepeatingView categories = new RepeatingView("categories");
		addOrReplace(categories);

		List<Category> toChoose = null;
		
		if(selected != null) {
			toChoose = InfomaresmeApplication.getQAApplication().getCategoriesDao().findChildrem(selected);
		} else {
			toChoose = findTopLevel();
		}
		
		if(toChoose.size() > 0) {
			for(Category category: toChoose) {
				WebMarkupContainer wm  = new WebMarkupContainer(categories.newChildId());
				categories.add(wm);
				wm.add(new CategoryLinkPanelNoArrows("category", category) {
					
					private static final long serialVersionUID = 1L;
	
					@Override
					public void onClick(AjaxRequestTarget target) {
						selected = getCategory();
						CategoriesListPanel.this.onClick(target);
					}
				});
			}
		} else {
			categories.setVisible(false);
			WebMarkupContainer wm  = new WebMarkupContainer(categories.newChildId());
			categories.add(wm);
			wm.add(new Label("category", "NONE"));
		}
				
		super.onBeforeRender();
	}

	protected abstract List<Category> findTopLevel();
	
	public abstract void onClick(AjaxRequestTarget target);

	public Category getSelected() {
		return selected;
	}

	public void setSelected(Category selected) {
		this.selected = selected;
	}
}
